package com.plugin.storage.base;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.plugin.storage.storage.JacksonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.util.concurrent.TimeUnit;

public class SdkCache {

    private static final Logger LOGGER = LoggerFactory.getLogger(SdkCache.class);

    private static Cache<String, AuthToken> tokenCache = CacheBuilder.newBuilder()
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .maximumSize(10)
            .build();

    private static Cache<String, String> urlCache = CacheBuilder.newBuilder()
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .maximumSize(1000)
            .build();

    private static Jedis jedis;
    private static boolean hasJedis = false;

    public static void setJedis(Jedis newJedis) {
        jedis = newJedis;
        hasJedis = true;
    }

    public static AuthToken getToken(String roleArn) {
        if (hasJedis) {
            JacksonUtils.toObject(jedis.get(roleArn), AuthToken.class);
        }
        return tokenCache.getIfPresent(roleArn);
    }


    public static AuthToken putToken(String roleArn, AuthToken token) {
        if (hasJedis) {
            jedis.setex(roleArn, token.getTTL(), JacksonUtils.toJSON(token));
            return token;
        }
        tokenCache.put(roleArn, token);
        return token;
    }

    public static String getUrl(String key) {
        return urlCache.getIfPresent(key);
    }

    public static String putUrl(String key, String accessUrl) {
        urlCache.put(key, accessUrl);
        return accessUrl;
    }
}
